package fr.umlv.m2.android.quizz.player;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import fr.umlv.m2.android.quizz.HomepageActivity;
import fr.umlv.m2.android.quizz.R;
import fr.umlv.m2.android.quizz.database.User;
import fr.umlv.m2.android.quizz.database.UserDb;

public class EditPlayerActivity extends Activity {
	/**
	 * The list of players.
	 */
	private List<User> players;
	/**
	 * The list of players name.
	 */
	private List<String> playersName;
	/**
	 * The players spinner.
	 */
	private Spinner playersSpin;
	/**
	 * The add player button.
	 */
	private Button addPlayer;
	/**
	 * The rename player button.
	 */
	private Button renamePlayer;
	/**
	 * The delete player button.
	 */
	private Button deletePlayer;
	/**
	 * The validate player button.
	 */
	private Button validatePlayer;
	
	/**
	 * The spinner adapter.
	 */
	private ArrayAdapter<String> adapterSpin;
	
	/**
	 * The intent.
	 */
	private Intent intent;
	/**
	 * The user database object.
	 */
	private UserDb userDb;
	/**
	 * The user id.
	 */
	private User user;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.edit_player);
		
		this.playersSpin = (Spinner)findViewById(R.id.editPlayerSpinner);
		this.addPlayer = (Button)findViewById(R.id.editPlayerAddPlayerButton);
		this.renamePlayer = (Button)findViewById(R.id.editPlayerRenamePlayerButton);
		this.deletePlayer = (Button)findViewById(R.id.editPlayerDeletePlayerButton);
		this.validatePlayer = (Button)findViewById(R.id.editPlayerValidatePlayerButton);
		
		this.intent = this.getIntent();
		this.userDb = new UserDb(this);
		this.userDb.open();

		this.user = userDb.getUserWithId(this.intent.getExtras().getLong("userId"));
		if(userDb.getNbUser() < 2) {
			deletePlayer.setEnabled(false);
		}
		this.userDb.close();
		
		this.intent = new Intent(this, HomepageActivity.class);
		this.spinnerReinitialization();
		
		this.playersSpin.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				userDb.open();
				
				user = userDb.getUserWithName(parent.getItemAtPosition(position).toString());
				
				userDb.close();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {}
		});
		
		this.addPlayer.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				LayoutInflater factory = LayoutInflater.from(EditPlayerActivity.this);
				final View addPlayerDialogView = factory.inflate(R.layout.add_player_dialog, null);
				
				AlertDialog.Builder builder = new AlertDialog.Builder(EditPlayerActivity.this);
				builder.setView(addPlayerDialogView);
				builder.setTitle(R.string.editPlayerAddPlayerDialogTitleText);
				
				builder.setPositiveButton(R.string.editPlayerAddPlayerDialogValidateButton, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						EditText newUserNameEditText = (EditText)addPlayerDialogView.findViewById(
								R.id.addPlayerDialogEditText
						);
						
						String newUserName = newUserNameEditText.getText().toString();
						if(!newUserName.equals("")) {
							User newUser = new User(newUserName);
							userDb.open();
							userDb.insertUser(newUser);
							userDb.close();
							user = newUser;
							spinnerReinitialization();
	
							
							if(!deletePlayer.isEnabled()) {
								deletePlayer.setEnabled(true);
							}
						}
					}
				});
				
				builder.setNegativeButton(R.string.dialogCancelButton, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {}
				});
				
				builder.show();
			}
		});
		
		this.renamePlayer.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				LayoutInflater factory = LayoutInflater.from(EditPlayerActivity.this);
				final View renamePlayerDialogView = factory.inflate(R.layout.rename_player_dialog, null);
				
				AlertDialog.Builder builder = new AlertDialog.Builder(EditPlayerActivity.this);
				builder.setView(renamePlayerDialogView);
				builder.setTitle(R.string.editPlayerRenamePlayerDialogTitleText);
				
				builder.setPositiveButton(R.string.editPlayerRenamePlayerDialogValidateButton, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {						
						EditText newUserNameEditText = (EditText)renamePlayerDialogView.findViewById(
								R.id.renamePlayerDialogEditText
						);
						
						String newUserName = newUserNameEditText.getText().toString();
						if(!newUserName.equals("")) {
							user.setName(newUserName);
							userDb.open();
							userDb.updateUser(user.getId(), user);
							userDb.close();
							spinnerReinitialization();
						}
					}
				});
				
				builder.setNegativeButton(R.string.dialogCancelButton, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {}
				});
				
				builder.show();
			}
		});
		
		this.deletePlayer.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				userDb.open();
				
				if(userDb.removeUserWithID(user.getId()) > 0) {
					players.remove(user);
					playersName.remove(user.getName());
					
					adapterSpin = new ArrayAdapter<String>(
							EditPlayerActivity.this, android.R.layout.simple_spinner_item, playersName
					);
					adapterSpin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					playersSpin.setAdapter(adapterSpin);
	
					playersSpin.setSelection(0);
					user = userDb.getUserWithName((String)playersSpin.getSelectedItem());
					
					if(userDb.getNbUser() < 2) {
						deletePlayer.setEnabled(false);
					}
				}
				
				userDb.close();
			}
		});
		
		this.validatePlayer.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				intent.putExtra("userId", user.getId());
				startActivity(intent);
			}
		});
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		
		intent.putExtra("userId", user.getId());
		startActivity(intent);
	}
	
	private void spinnerReinitialization() {
		this.userDb.open();
		this.players = this.userDb.getAllUsers();
		this.userDb.close();
		
		this.playersName = new ArrayList<String>();
		for(User user : this.players) {
			this.playersName.add(user.getName());
		}
		
		this.adapterSpin = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, this.playersName
		);
		this.adapterSpin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		this.playersSpin.setAdapter(this.adapterSpin);

		this.playersSpin.setSelection(this.playersName.indexOf(this.user.getName()));
	}
}
